'use strict';

const Service = require('egg').Service;
const NotFoundException = require("../exception/not_found");
const { Op } = require("sequelize");

class WordFavoritesService extends Service {
  // 添加收藏
  async create(userId, wordId) {
    const { ctx } = this;
    return await ctx.model.WordFavorites.create({
      user_id: userId,
      word_id: wordId,
    });
  }

  // 取消收藏
  async delete(userId, wordId) {
    const { ctx } = this;
    return await ctx.model.WordFavorites.destroy({
      where: {
        user_id: userId,
        word_id: wordId,
      },
    });
  }

  // 检查是否已收藏
  async isFavorited(userId, wordId) {
    const { ctx } = this;
    const count = await ctx.model.WordFavorites.count({
      where: {
        user_id: userId,
        word_id: wordId,
      },
    });
    return count > 0;
  }

  // 获取用户收藏列表
  async getUserFavorites(userId, page = 1, pageSize = 10) {
    const { ctx } = this;
    const { count, rows } = await ctx.model.WordFavorites.findAndCountAll({
      where: { user_id: userId },
      include: [
        {
          model: ctx.model.Word,
          as: 'english_word',
        },
      ],
      offset: (page - 1) * pageSize,
      limit: pageSize,
      order: [[ 'created_at', 'DESC' ]],
    });
    return {
      total: count,
      list: rows.map(item => item.english_word),
      page,
      pageSize,
    };
  }
}

module.exports = WordFavoritesService;